package xyz.ibenben.zhongdian.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import xyz.ibenben.zhongdian.common.annotation.SystemControllerLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.entity.CompanyInfo;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;
import xyz.ibenben.zhongdian.system.form.CompanyInfoForm;
import xyz.ibenben.zhongdian.system.service.CompanyInfoService;
import xyz.ibenben.zhongdian.system.service.impl.RedisService;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 公司信息控制类
 * 提供了一些基本的服务，如初始化、获取公司信息列表等方法。
 * spring mvc思想 通过controller来调用service里的方法，
 * service里的方法再通过调用Dao来实现对数据的操作
 * 返回值统统是String类型的返回页面有统一的安排方便代码提取
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Slf4j
@Controller
@SessionAttributes("companyInfoForm")
@RequestMapping("/companyInfo")
public class CompanyInfoController extends BaseController {
    /**
     * 实体名称
     */
    private static final String ENTITYNAME = "companyInfo";

    @Resource
    private CompanyInfoService companyInfoService;
    @Resource
    private RedisService redisService;

    @InitBinder
    public void binder(WebDataBinder binder) {
        //转换日期
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // CustomDateEditor为自定义日期编辑器
        binder.registerCustomEditor(Date.class, "createDate", new CustomDateEditor(dateFormat, true));

    }

    /**
     * 初始化
     *
     * @param map             参数
     * @param companyInfoForm 条件参数
     */
    @ModelAttribute
    public void init(Model map, @ModelAttribute CompanyInfoForm companyInfoForm, HttpSession session) {
        map.addAttribute("provinceList", redisService.get("provinceList"));
        map.addAttribute("cityList", redisService.get("cityList"));
        map.addAttribute("regionList", redisService.get("regionList"));
        CompanyInfoForm newCompanyInfoForm = new CompanyInfoForm();
        if (companyInfoForm != null) {
            newCompanyInfoForm = companyInfoForm;
        }
        SysUser user = (SysUser) session.getAttribute(Constants.SESSION);
        if (user != null && user.getSysRole() != null) {
            newCompanyInfoForm.setCompanyId(user.getSysRole().getCompanyId());
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newCompanyInfoForm);
    }

    /**
     * 获取公司信息列表
     *
     * @param map             参数
     * @param companyInfoForm 条件参数
     * @return 页面
     */
    @RequestMapping(value = "/getAll")
    @SystemControllerLog(description = "获取公司信息列表")
    public String getAll(Model map, @ModelAttribute CompanyInfoForm companyInfoForm) {
        log.info("getAll param CompanyInfoForm: {}", companyInfoForm.toString());
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), companyInfoForm);
        Page<CompanyInfo> page = new Page<>(companyInfoForm.getPageIndex(), companyInfoForm.getPageSize());
        IPage<CompanyInfo> result = companyInfoService.findAll(page, companyInfoForm);
        map.addAttribute(Constants.PI, result);
        return String.format(Constants.LISTPAGE, ENTITYNAME);
    }

    /**
     * 删除公司信息记录
     *
     * @param id 主键
     * @return 页面
     */
    @RequestMapping(value = "/delete")
    @SystemControllerLog(description = "删除公司信息记录")
    public String delete(@RequestParam("id") Long id, SessionStatus status) {
        companyInfoService.removeById(id);
        status.setComplete();
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 删除公司信息列表
     *
     * @param companyInfoForm 条件参数
     * @return 页面
     */
    @RequestMapping("/deleteAll")
    @SystemControllerLog(description = "删除公司信息列表")
    public String deleteAll(@ModelAttribute CompanyInfoForm companyInfoForm, SessionStatus status) {
        if (companyInfoForm.getSelectIds() != null) {
            String[] ids = companyInfoForm.getSelectIds().split(Constants.COMMA);
            for (String id : ids) {
                companyInfoService.removeById(Long.parseLong(id));
            }
        }
        status.setComplete();
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 打开公司信息添加页面
     *
     * @param map 参数
     * @return 页面
     */
    @GetMapping("/add")
    @SystemControllerLog(description = "打开公司信息添加页面")
    public String openAddPage(Model map) {
        map.addAttribute(ENTITYNAME, new CompanyInfo());
        return String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 保存公司信息添加记录
     *
     * @param companyInfo   实体
     * @param bindingResult 校验
     * @return 页面
     */
    @PostMapping("/add")
    @SystemControllerLog(description = "保存公司信息添加记录")
    public String postAddMessage(@Valid @ModelAttribute(ENTITYNAME) CompanyInfo companyInfo,
                                 BindingResult bindingResult, SessionStatus status) {
        if (StringUtils.isNotBlank(companyInfo.getCompanyName())) {
            List<CompanyInfo> list = companyInfoService.findByCompanyName(companyInfo.getCompanyName());
            if (null != list && !list.isEmpty()) {
                bindingResult.rejectValue("companyName", "misFormat", "这个公司名称已经存在了！请更改!");
            }
        }
        if (!bindingResult.hasErrors()) {
            companyInfoService.save(companyInfo);
            status.setComplete();
            return String.format(Constants.REDIRECT, ENTITYNAME);
        }
        return String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 打开公司信息修改页面
     *
     * @param map 参数
     * @param id  主键
     * @return 页面
     */
    @GetMapping("/edit")
    @SystemControllerLog(description = "打开公司信息修改页面")
    public String openEditPage(Model map, @RequestParam("id") Long id) {
        map.addAttribute(ENTITYNAME, companyInfoService.findByKey(id));
        return String.format(Constants.EDITPAGE, ENTITYNAME);
    }

    /**
     * 更新公司信息修改记录
     *
     * @param companyInfo   实体
     * @param bindingResult 校验
     * @return 页面
     */
    @PostMapping("/edit")
    @SystemControllerLog(description = "更新公司信息修改记录")
    public String postEditMessage(@Valid @ModelAttribute(ENTITYNAME) CompanyInfo companyInfo,
                                  BindingResult bindingResult, SessionStatus status) {
        CompanyInfo info = companyInfoService.findByKey(companyInfo.getId());
        if (!info.getCompanyName().equals(companyInfo.getCompanyName())) {
            List<CompanyInfo> list = companyInfoService.findByCompanyName(companyInfo.getCompanyName());
            if (null != list && !list.isEmpty()) {
                bindingResult.rejectValue("companyName", "misFormat", "这个公司名称已经存在了！请更改!");
                return String.format(Constants.EDITPAGE, ENTITYNAME);
            }
        }
        if (!bindingResult.hasErrors()) {
            companyInfoService.updateById(companyInfo);
            status.setComplete();
            return String.format(Constants.REDIRECT, ENTITYNAME);
        } else {
            return String.format(Constants.EDITPAGE, ENTITYNAME);
        }
    }

    /**
     * 浏览公司信息记录
     *
     * @param map             参数
     * @param id              主键
     * @param companyInfoForm 条件参数
     * @return 页面
     */
    @GetMapping("/view")
    @SystemControllerLog(description = "浏览公司信息记录")
    public String openViewPage(Model map, @RequestParam("id") Long id,
                               @ModelAttribute CompanyInfoForm companyInfoForm) {
        CompanyInfo info = companyInfoService.findByKey(id);
        map.addAttribute(ENTITYNAME, info);
        return String.format(Constants.VIEWPAGE, ENTITYNAME);
    }

}

